package com.atguigu.split;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.Arrays;
import java.util.List;

/**
 * @author yhm
 * @create 2024-04-02 15:35
 */
public class Test02_OutputTag {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 2. 读取数据源
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 8, 9, 5, 2, 3);
        DataStreamSource<Integer> streamSource = env.fromCollection(list);

        // 3. 处理数据

        OutputTag<Integer> integerOutputTag1 = new OutputTag<Integer>("1"){};
        OutputTag<Integer> integerOutputTag2 = new OutputTag<>("2", Types.INT);

        SingleOutputStreamOperator<Integer> processStream = streamSource.process(new ProcessFunction<Integer, Integer>() {
            // process是最最底层的API 可以实现其他一切方法(不包括特殊功能)
            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);
            }

            @Override
            public void processElement(Integer value, Context ctx, Collector<Integer> out) throws Exception {
                // 调用两个侧输出流
                if (value % 2 == 0) {
                    ctx.output(integerOutputTag2, value);
                } else {
                    ctx.output(integerOutputTag1, value);
                }
                out.collect(value);

            }


            @Override
            public void close() throws Exception {
                super.close();
            }
        });

        processStream.print();

        // 调用侧输出流
        SideOutputDataStream<Integer> numStream1 = processStream.getSideOutput(integerOutputTag1);
        SideOutputDataStream<Integer> numStream2 = processStream.getSideOutput(integerOutputTag2);
        numStream1.print("奇数为:");
        numStream2.print("偶数为:");

        // 4. 输出

        // 5. 执行环境
        env.execute();
    }
}
